package com.changgou.pay.service.impl;

import com.changgou.pay.service.WXPaService;
import com.github.wxpay.sdk.WXPay;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

@Service
public class WXPayServiceImpl implements WXPaService {
    @Autowired
    private WXPay wxPay;
    @Value("${wxpay.notify_url}")
    private String notify_url;

    @Override
    public Map nativePay(String orderId, Integer money) {
        try {
            //封装请求参数
            HashMap<String, String> map = new HashMap();
            map.put("body","畅购");
            map.put("out_trade_no",orderId);

            //后续需要进行实际支付操作,不按照前台数据进行支付,这里我们设置为0.01元
            //前端传过来的单位是元,需要的转换成分
            BigDecimal payMoney = new BigDecimal("0.01");//注意传入字符串类型
            BigDecimal fen = payMoney.multiply(new BigDecimal("100"));//1.00
            //微信支付支持最小单位为分,没有小数点,所以需要取整
            BigDecimal total_fee= fen.setScale(0, BigDecimal.ROUND_UP);

            map.put("total_fee",String.valueOf(total_fee));//单位为分
            map.put("spbill_create_ip","127.0.0.1");
            map.put("notify_url",notify_url);
            map.put("trade_type","NATIVE");
            Map<String, String> result = wxPay.unifiedOrder(map);
            return result;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }

    //查询微信支付情况
    @Override
    public Map queryOrder(String orderId) {
        try {
            HashMap<String, String> map = new HashMap<>();
            map.put("out_trade_no",orderId);
            Map<String, String> queryResult = wxPay.orderQuery(map);
            return queryResult;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }

    }

    @Override
    public Map closeOrder(String orderId) {
        try {
            Map<String, String> map=new HashMap<>();
            map.put("out_trade_no",orderId);
            Map<String, String> resultMap = wxPay.closeOrder(map);
            return resultMap;
        }catch (Exception e){
            return null;
        }
    }
}
